<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="addDialog.isDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="roleList">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <!-- 条件判断 -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template v-slot="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              size="mini"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>  {{ row.state === 1 ? "已启用" : "未启用" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="editOk(row)">确定</el-button>
              <el-button size="mini" @click="editClose(row)">取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态 -->
              <el-button size="mini" type="text" @click="premDialog.methods.btnPrem(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="row.isEdit = true">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="delRole(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :page-size.sync="pages.pagesize"
          :current-page.sync="pages.page"
          :total="pages.total"
          layout="prev, pager, next"
          @current-change="getRoleList"
        />
      </el-row>
    </div>
    <!-- 分配权限弹窗 -->
    <el-dialog width="500px" title="分配权限" :visible.sync="premDialog.isDialog">
      <el-tree
        ref="assignPremDialog"
        node-key="id"
        :data="premDialog.permData"
        :props="{label: 'name'}"
        show-checkbox
        default-expand-all
        :default-checked-keys="premDialog.permIds"
        check-strictly
      />
      <template>
        <el-button type="primary" size="mini" @click="premDialog.methods.ok">确定</el-button>
        <el-button size="mini" @click="premDialog.isDialog = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 新增的弹窗 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="addDialog.isDialog">
      <!-- 表单内容 -->
      <el-form ref="refAddDialogForm" :model="addDialog.data.form" :rules="addDialog.data.rules" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addDialog.data.form.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            v-model="addDialog.data.form.state"
            size="mini"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="addDialog.data.form.description"
            type="textarea"
            :rows="3"
            style="width:300px"
            size="mini"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="addDialog.methods.ok">确定</el-button>
              <el-button size="mini" @click="addDialog.methods.close">重置并关闭</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, postRole, putRole, delRole, getRole, putRlePrem } from '@/api/role'
import { transListToTreeData } from '@/utils/index.js'
import { getPermissionList } from '@/api/permission'
import _ from 'lodash'

export default {
  name: 'RolePage',
  data() {
    return {
      roleList: [], // 角色列表
      premDialog: {
        isDialog: false, // 弹窗显示
        permIds: [], //
        permData: [], // 权限点列表
        roleId: null, // 暂存用户Id
        methods: {
          btnPrem: async(id) => {
            // 清空权限点列表
            this.premDialog.permIds = []
            console.log(id, '角色ID')
            const asPerm = await getPermissionList()
            this.premDialog.permData = await transListToTreeData(asPerm, 0)
            console.log(this.premDialog.permData, '权限点列表')
            const res = await getRole(id)
            this.premDialog.permIds = []
            this.premDialog.permIds = res.permIds
            console.log(this.premDialog.permIds, '用户默认选中的权限点')
            this.premDialog.isDialog = true
            this.premDialog.roleId = id
          },
          ok: async() => {
            // this.$refs.assignPremDialog.getCheckedKeys() 获取被选中的元素 为一个数组
            await putRlePrem({ id: this.premDialog.roleId, permIds: this.$refs.assignPremDialog.getCheckedKeys() })
            this.$message.success('分配权限成功')
            this.premDialog.isDialog = false
          }
        }

      },
      pages: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      addDialog: {
        isDialog: false,
        data: {
          form: {
            name: '',
            description: '',
            state: 0 // 默认0 关闭 0 打开1
          },
          rules: Object.seal({
            name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
            description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
          })
        },
        methods: {
          ok: async() => {
            await this.$refs.refAddDialogForm.validate()
            console.log('添加表单校验通过')
            await postRole(this.addDialog.data.form)
            this.$message.success('添加成功')
            await this.getRoleList()
            this.addDialog.methods.close()
          },
          close: () => {
            this.addDialog.data.form.state = 0
            this.$refs.refAddDialogForm.resetFields()
            this.addDialog.isDialog = false
          }
        }
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 删除角色功能
    async delRole(id) {
      await delRole(id)
      this.$message.success('删除成功')
      if (this.roleList.length === 1) {
        this.pages.page--
      }
      this.getRoleList()
    },
    // 编辑状态下的 确认按钮
    async editOk(row) {
      if (row.editRow.name !== '' && row.editRow.description !== '') {
        await putRole({ id: row.id, ...row.editRow })
        this.$message.success('编辑成功')
        this.getRoleList()
        // ES-lint 报错单行关闭
        // eslint-disable-next-line require-atomic-updates
        row.isEdit = false
      } else {
        this.$message.error('角色名称与角色描述不能为空！')
      }
    },
    // 编辑状态下的 取消按钮
    editClose(row) {
      row.isEdit = false
      // row.editRow 是额外拷贝的缓存数据
      // 点击取消按钮 给缓存数据对象 进行重新赋值重置
      row.editRow = {
        ...row
      }
    },
    // 封装初始化数据请求方法
    async getRoleList() {
      const res = await getRoleList(_.omit(this.pages, ['total']))
      this.roleList = res.rows
      this.pages.total = res.total
      console.log(this.roleList, '角色管理_list')
      console.log(this.pages.total, '角色管理_total')
      this.roleList.forEach(v => {
        // 不是响应式
        // v.isEdit = false
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象, 属性名称, 初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(v, 'isEdit', false)
        // 给循环下来的每一项 添加一个对象，缓存对象，用户修改的也是修改的 对象里的数据，不会影响到原本数据
        this.$set(v, 'editRow', {
          name: v.name,
          state: v.state,
          description: v.description
        })
      })
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
